package cn.com.connext.scrm.service;

import cn.com.connext.scrm.config.Constants;
import cn.com.connext.scrm.domain.master.Activity;
import cn.com.connext.scrm.domain.master.AwardRecord;
import cn.com.connext.scrm.repository.master.ActivityRepository;
import cn.com.connext.scrm.repository.master.AwardRecordRepository;
import cn.com.connext.scrm.utils.RandomUtils;
import cn.com.connext.scrm.utils.RedisUtils;
import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.cloudfoundry.com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.cloudfoundry.com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import rx.exceptions.Exceptions;
import springfox.documentation.service.MediaTypes;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.PrivateKey;
import java.text.SimpleDateFormat;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.List;

/***
 *  created by wangzhan on 2018/01/24
 *
 *  小程序 活动管理
 */
@Service
public class WxAPIService{
    private final static Logger log = LoggerFactory.getLogger(WxAPIService.class);

    @Autowired
    private RedisUtils redisUtils;

    private final static int riskyCode=87014;

//    @Autowired
    private  RestTemplate restTemplate=new RestTemplate();


    private  String  getAccessToken(){
//        String accessKey="mini_program_access_token";
//        Object accessTokenCache=redisUtils.get(accessKey);
//        if(accessTokenCache!=null){
//            return (String)accessTokenCache;
//        }else{
            String requestUrl = Constants.GetAccessTokenUrl.replace("APPID", Constants.APPID).replace("APPSECRET", Constants.SECRET);
            log.info(" start request URL = {} ", requestUrl);
            JSONObject result=restTemplate.getForEntity(requestUrl, JSONObject.class).getBody();
            String accessToken=result.getString("access_token");
//            redisUtils.set(accessKey,accessToken,7200L);
            return accessToken;
       // }

    }

    public JSONObject msgSafeCheck(String  msg){
        String requestUrl = Constants.WxMsgCheckUrl.replace("ACCESS_TOKEN", getAccessToken());
        log.info(" start request URL = {} ", requestUrl);
        HttpHeaders headers = new HttpHeaders();
         MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
         headers.setContentType(type);
         headers.add("Accept", MediaType.APPLICATION_JSON.toString());
         JSONObject jsonObj = new JSONObject();
         jsonObj.put("content",msg);
        HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
        JSONObject result=restTemplate.postForEntity(requestUrl,formEntity,JSONObject.class).getBody();
        log.info("result:{}", result);
        return result;

    }

    public JSONObject imgaeSafeCheck(MultipartFile file)   throws Exception{
        String requestUrl = Constants.WxImageCheckUrl.replace("ACCESS_TOKEN", getAccessToken());
        File f=new File(file.getOriginalFilename());
        FileUtils.writeByteArrayToFile(f,file.getBytes() );
        FileSystemResource resource = new FileSystemResource(f);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
        parts.add("media", resource);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(parts, headers);
        JSONObject result=restTemplate.exchange(requestUrl,HttpMethod.POST,requestEntity,JSONObject.class).getBody();
        log.info(result.toJSONString());
        f.deleteOnExit();
        return  result;
    }

    public String getThisAccessToken() {
        String accessToken = getAccessToken();
        return accessToken;
    }

}
